#include "vehicle.h"
#include "ui_vehicle.h"
#include "ui_search.h"
#include "dbmanager.h"
#include "entity/vehicleentity.h"

Vehicle::Vehicle(QWidget *parent) :
    QWidget(parent), ui(new Ui::Vehicle)
{
    ui->setupUi(this);
    owner_id = -1;

    connect(ui->chooseButton, SIGNAL(clicked()), this, SLOT(slotChooseOwner()));
    connect(ui->okButton, SIGNAL(clicked()), this, SLOT(slotOkClicked()));
}

Vehicle::~Vehicle()
{
    delete ui;
}

void Vehicle::slotChooseOwner()
{
    search = new Search(0);
    connect(search->getOkButton(), SIGNAL(clicked()), this, SLOT(slotOwnerSelected()));
    DBManager * dbm = DBManager::getGlobal();
    model = new QSqlTableModel(search);
    dbm->allOwners(model);
    search->getTableView()->setModel(model);
    search->setTitle("Search Owner");
    search->setWindowModality(Qt::ApplicationModal);
    search->show();
}

void Vehicle::slotOwnerSelected()
{
    QItemSelectionModel * selectionModel = search->getTableView()->selectionModel();
    int selectedRow = selectionModel->currentIndex().row();

    QSqlRecord record = model->record(selectedRow);
    owner_id = record.value("owner_id").toInt();
    ui->ownerName->setText(record.value("owner_name").toString());
    ui->ownerAddress->setText(record.value("address1").toString());
    ui->ownerCity->setText(record.value("city1").toString());
}

void Vehicle::slotOkClicked()
{
    VehicleEntity * vehicle = new VehicleEntity();
    vehicle->setOwnerId(owner_id);
    vehicle->setVehicleRegNo(ui->regNoText->text());
    vehicle->setVehicleEngNo(ui->engineNoText->text());
    vehicle->setVehicleChsNo(ui->chassyNoText->text());
    vehicle->setVehicleModel(ui->vehicleModelText->text());
    vehicle->setVehicleDesc(ui->vehicleModelText->text());
    vehicle->setDeleted(0);

    DBManager * dbm = DBManager::getGlobal();
    dbm->insertVehicle(vehicle);

    delete vehicle;
}

